package org.shj.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.shj.util.StoreUtils;
import org.shj.util.StringUtils;

/**
 * Servlet Filter implementation class TokenFilter
 */
@WebFilter(filterName="TokenFilter", urlPatterns="/*")
public class TokenFilter implements Filter {

    /**
     * Default constructor. 
     */
    public TokenFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		
		String uri = req.getRequestURI();
		//System.out.println("req.getRequestURI() is: " + uri);
		//System.out.println("req.getContextPath() is: " + req.getContextPath());
		
		if(uri.endsWith(".css") || uri.endsWith(".js")){
			chain.doFilter(request, response);
			return;
		}
		
		// 如果是退出操作，则继续
		if(uri.contains("/logout")){
			chain.doFilter(request, response);
			return;
		}
		
		if(uri.contains("/login")){
			chain.doFilter(request, response);
			return;
		}
		
		if(uri.contains("/validate")){
			chain.doFilter(request, response);
			return;
		}
		
		Boolean hasLogin = (Boolean)req.getSession().getAttribute("isLogin");
		if(hasLogin != null && hasLogin){//如果已经登陆
			//某个系统登陆成功后，另外一个系统登陆时，会走到这
            System.out.println("已登陆");
            String returnUrl = request.getParameter("returnUrl");
            if(StringUtils.isEmpty(returnUrl)){
            	response.getWriter().println("只提供登陆退出操作。请设置登陆成功后需返回的 URL。");
            	return;
            }
            
            String token = StoreUtils.getToken(req.getSession().getId());
            res.sendRedirect(returnUrl + "?token=" + token);
        }else{
        	System.out.println("尚未登陆");
        	request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
